package com.trabpoo.megamanxrunner;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Arquivo {

	FileReader fileR;
	BufferedReader buffR;
	FileWriter fileW;
	BufferedWriter buffW;

	public List<String> valores = new ArrayList<String>();
	
	int x, cont, flag;
	public int[] pontuacao = new int[11];
	
	public void lerArquivo(String input, int pontuation){
		try {
			fileR = new FileReader("ranking2.txt");
			valores.clear();
			buffR = new BufferedReader(fileR);
			cont = 0;
			x = 0;
			flag = 0;
			//Coloco a pontuacao e o nome na linha de baixo.
			while(buffR.ready()){
				String str2 = buffR.readLine();
				String str = buffR.readLine();
				int pt = Integer.parseInt(str2);
				if ((pontuation >= pt)&&(flag == 0)) {
					flag = 1;
					pontuacao[x] = pontuation;
					x++;
					valores.add(input);
				}
				pontuacao[x] = pt;
				x++;
				valores.add(str);
			}
			if (flag == 0) {
				valores.add(input);
				pontuacao[x] = pontuation;
			}
			buffR.close();
			escreveArquivo();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	public void escreveArquivo() {
		String var;
		int temp;
		try {
			fileW = new FileWriter("ranking2.txt");
			buffW = new BufferedWriter(fileW);
			temp = valores.size();
			if (temp > 10) {
				temp = 10;
			}
			//Escreve apenas os 10 primeiros
			for(x = 0; x < temp; x++) {
				var = String.valueOf(pontuacao[x]);
				buffW.write(var);
				buffW.newLine();
				buffW.write(valores.get(x));
				if (x < 9) {
					buffW.newLine();
				}
			}
			buffW.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public List<String> getNome () {
		try {
			fileR = new FileReader("ranking2.txt");
			buffR = new BufferedReader(fileR);
			valores.clear();
			while(buffR.ready()){
				String str = buffR.readLine();
				valores.add(str);
			}
			buffR.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return (valores);
	}
	
}